<template>
  <div class="search-modal">
    <el-popover
      ref="popover"
      popper-class="el-popper-search"
      :placement="placement"
      :width="width"
      :disabled="disabled"
      v-model="dialogAdd"
      :trigger="trigger"
    >
      <div class="SiruiModalHeight" :class="className">
        <h1>内容区域</h1>
      </div>
      <el-input
        class="el-input-table"
        :readonly="false"
        slot="reference"
        :placeholder="placeholder"
        :disabled="disabled"
        v-model="defaultValue"
        @change="blurInput"
        @focus="focusModal"
        clearable
        @clear="resetBtnClick"
        :maxLength="isReadOnly ? '0' : ''"
      >
        <i
          style="cursor: pointer"
          slot="suffix"
          @click="handleIconClick"
          :class="{ 'el-icon-arrow-up': true, 'el-select__caret': true, 'is-reverse': dialogAdd }"
        ></i>
      </el-input>
    </el-popover>
  </div>
</template>
<script>
export default {
  props: {
    width: {
      type: String,
      default: () => '800px',
    },
    page: {
      type: Boolean,
      default: () => true,
    },
    //查询字段
    query: {
      type: Object,
      default: () => {},
    },
    //搜索区域的内容
    searchColumns: {
      type: Array,
      default: () => [],
    },
    // 请求方式，默认为post
    type: {
      type: String,
      default: () => 'post',
    },
    //查询的接口
    API: {
      type: String,
      default: () => '',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    disabled: {
      type: Boolean,
      default: () => false,
    },
    model: {
      type: String,
      default: () => '',
    },
    columnList: {
      type: Array,
      default: () => [],
    },
    buttonList: {
      type: Array,
      default: () => [],
    },
    placement: {
      type: String,
      default: () => 'top',
    },
    propCode: {
      type: String,
      default: '',
    },
    propName: {
      type: String,
      default: '',
    },
    isReadOnly: {
      type: Boolean,
      default: () => true,
    },
    //是否单选
    isMultiple: {
      type: Boolean,
      default: () => false,
    },
    //解析extendMap
    parseExtendMap: {
      type: Boolean,
      default: () => false,
    },
    //默认值
    currentValue: {
      type: String,
      default: () => '',
    },
    //额外参数
    extraData: {
      type: Object,
      default: () => {},
    },
    //默认选中
    checkRowKeys: {
      type: Array,
      default: () => [],
    },
    //抛出重置方法
    resetModelFun: {
      type: String,
      default: () => '',
    },
    // 可关闭参数
    dbclone: {
      type: Boolean,
      default: () => false,
    },
    // 点击方式
    trigger: {
      type: String,
      default: () => 'click',
    },
    //不调用接口时传入options
    options: {
      type: Array,
      default: () => [],
    },
    // 禁止没有查询条件搜索
    disableNoSearchData: {
      type: Boolean,
      default: () => false,
    },
    // 是否默认初始化查询
    initShow: {
      type: Boolean,
      default: () => true,
    },
    labelWidth: {
      type: String,
      default: '90px',
    },
    className: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      load: false,
      tableData: [],
      dialogAdd: false,
      showTable: this.options ? !this.options[0] : {},
      icon: 'el-icon-arrow-down',
      multipleSelection: [],
      defaultValue: this.currentValue,
      schemeRulesForm: { ...this.query },
      newCheckRowKeys: [],
      name: this.propName,
      resetFlag: false, //重置标志
      leftPos: '',
    };
  },
  methods: {
    changeQuery(newValue) {
      this.$emit('changeQuery', newValue);
    },
    setPropName(propName) {
      this.name = propName;
    },
    //获取数据
    getData() {
      if (this.options && this.options[0]) {
        this.tableData = this.options;
        return;
      }
      const query = this.handleData();
      /* if(this.disableNoSearchData && XEUtils.isEmpty(filterEmpty(query))){
        return;
      } */
      if (this.page) {
        query.pageSize = this.$refs.siruiTable.page.pageSize;
        query.pageNum = this.$refs.siruiTable.page.pageNum;
      }
      this.load = true;
      this.newCheckRowKeys = [];
      this.$axios[this.type](this.API, Object.assign(query, this.extraData)).then((res) => {
        this.load = false;
        if (0 == res.data.code) {
          if (this.page) {
            //有些分页接口数据返回的是records
            if (XEUtils.has(res.data.data, 'list')) {
              this.tableData = res.data.data.list;
            } else if (XEUtils.has(res.data.data, 'data')) {
              this.tableData = res.data.data;
            } else {
              this.tableData = res.data.data.records;
            }
            if (this.extraData?.calAmount) {
              this.tableData.forEach((item) => {
                item.remainAmount = this.$cal.calCommon(item.contractTotalAmount, item.registerAmount, '-', 'amount');
              });
            }
            if (this.parseExtendMap) {
              this.tableData.forEach((item) => {
                if (item.extendMap && item.extendMap.length != 0) {
                  Object.keys(item.extendMap).forEach((key) => {
                    if (item.extendMap[key]) {
                      item[key] = item.extendMap[key];
                    }
                  });
                }
              });
            }
            this.$refs.siruiTable.setPageTotal(res.data.data.total);
          } else {
            console.log('resTable', res.data.data);
            this.tableData = res.data.data;
          }
          //重新加载表格
          this.$refs.siruiTable.reloadTable(this.tableData);
          //设置默认选中
          if (this.multipleSelection.length != 0) {
            this.multipleSelection.forEach((item) => {
              this.newCheckRowKeys.push(this.propCode != '' ? item[`${this.propCode}`] : item.id);
            });
          } else {
            if (this.checkRowKeys.length != 0) {
              this.newCheckRowKeys = this.checkRowKeys;
            }
          }
        } else {
          this.$message({
            showClose: true,
            message: res.data.msg,
            type: 'error',
          });
        }
      });
    },
    //数据处理
    //将中文逗号转成英文逗号，去掉空数据
    handleData() {
      const query = Object.assign({}, this.$refs.siruiModalSearch.query);
      for (var key in query) {
        if (query[key] == '' || query[key] == null || query[key] == undefined) {
          //console.log(XEUtils.isArray(query[key]),key)
          //解决类型为selectMultiple时,不传默认为[],有值默认为字符串的问题
          this.searchColumns.forEach((item) => {
            if (item.type == 'selectMultiple' && Array.isArray(query[key]) && !query[key][0]) {
              query[key] = '';
            }
          });
        } else {
          let val = query[key].toString().replace(/，/gi, ',');
          let value = val.split(',');
          let list = [];
          //剔除空数据
          value.forEach((item) => {
            if (item) {
              list.push(item);
            }
          });
          query[key] = list.join(',');
        }
      }
      return query;
    },
    //搜索
    searchBtnClick() {
      if (this.page) {
        this.$refs.siruiTable.setPageNum(1);
      }
      this.getData();
    },
    //重置
    resetBtnClick() {
      this.resetFlag = true;
      if (this.page) {
        this.$refs.siruiTable.setPageNum(1);
        this.$refs.siruiTable.setPageSize(10);
      }
      this.multipleSelection = [];
      //手动清空页面所选数据
      this.defaultValue = this.currentValue;
      if (this.model) {
        this.$emit('setSearchModal', this.model, null);
      }
      this.$refs.siruiTable.clearSelectRecord();
      this.getData();
      if (this.resetModelFun == '') {
        return;
      }
      this.resetFlag = true;
      this.$emit('resetModelFun', { propCode: this.propCode });
    },
    resetClick() {
      this.defaultValue = this.currentValue;
      if (this.$refs.siruiModalSearch) {
        this.$refs.siruiModalSearch.resetForm('queryFrom');
      }
    },
    //每页条数
    handleSizeChange() {
      this.getData();
    },
    //第几页
    handleCurrentChange() {
      this.getData();
    },
    //调用接口排序
    sortChangeEvent({ column, property, order }) {
      console.info(column, property, order);
    },
    //双击事件
    dblclickEvent(value) {
      if (this.dbclone) this.dialogAdd = false;
      this.$emit('dblclickEvent', value);
      if (this.isMultiple) {
        //单选双击
        this.$refs.siruiTable.setRadioRow(value.row);
        this.addSure();
      }
    },
    //选中触发事件
    handleSelectionChange(row) {
      this.multipleSelection = row;
    },
    //确定
    addSure() {
      //解决再次打开 无法获取值的问题
      this.multipleSelection = this.isMultiple
        ? this.$refs.siruiTable.getRadioRecord()
          ? [this.$refs.siruiTable.getRadioRecord()]
          : null
        : this.$refs.siruiTable.getCheckboxRecords();
      let name = [];
      if (this.multipleSelection) {
        this.$emit('setSearchModal', this.model, this.multipleSelection);
        this.multipleSelection.forEach((item) => {
          name.push(item[`${this.name}`]);
        });
        name = name.join(',');
        this.defaultValue = name;
        this.dialogAdd = false;
        this.icon = 'el-icon-arrow-down';
      } else {
        this.$message({
          showClose: true,
          message: '没有数据',
          type: 'error',
        });
      }
    },
    blurInput() {
      let val = {};
      if (this.isReadOnly) {
        if (!this.defaultValue) {
          val[this.name] = this.defaultValue;
          this.$emit('setSearchModal', this.model, [val]);
        } else {
          this.$emit('setSearchModalInput', this.model, this.defaultValue);
        }
      } else {
        this.$emit('setSearchModalInput', this.model, this.defaultValue);
      }
    },
    focusModal() {
      if (this.trigger !== 'click') {
        this.dialogAdd = true;
      }
      if (this.initShow) this.getData();
      this.icon = 'el-icon-arrow-up';
    },
    handleIconClick() {
      if (this.dialogAdd) {
        this.blurModal();
      } else {
        this.focusModal();
      }
    },
    blurModal() {
      this.dialogAdd = false;
      this.icon = 'el-icon-arrow-down';
    },
    //点击按钮调用父页面方法
    chooseClick(buttonUrl, arr) {
      this.$emit('chooseClick', buttonUrl, arr);
    },
    //删除
    clearValue() {
      this.$emit('clearClick');
    },
    //返回列表数据
    returnTableData() {
      let data = {
        tableData: this.tableData,
        resetFlag: this.resetFlag,
      };
      return data;
    },
  },
  watch: {
    dialogAdd(value) {
      if (value) {
        this.showTable = true;
        this.icon = 'el-icon-arrow-up';
      } else {
        this.icon = 'el-icon-arrow-down';
      }
    },
    // 数据变化时给input默认值
    currentValue() {
      this.defaultValue = this.currentValue;
    },
    checkRowKeys() {
      if (this.checkRowKeys.length && this.tableData.length) {
        this.multipleSelection = this.tableData.filter((item) => {
          return this.checkRowKeys.includes(item[this.propCode || 'id']);
        });
      }
    },
    API: {
      handler() {
        //执行代码
        this.showTable = false;
        setTimeout(() => {
          this.showTable = true;
        }, 0);
      },
      immediate: false, //true就表示会立即执行
    },
  },
};
</script>
<style lang="scss" scoped>
$maintheme: #409eff;

.search-modal-footer {
  margin-top: 15px;
  text-align: center;
}

.el-button {
  border-radius: 2px;
}

.el-button--primary {
  background-color: $maintheme;
  border-color: $maintheme;
}

.SiruiModalHeight {
  // max-height: 480px;
  // overflow-y: auto;
  // overflow-x: hidden;
}
.SiruiModalHeight {
  // ::v-deep .vxe-table--body-wrapper {
  //   height: revert !important;
  //   // overflow-y: auto;
  // }
  // ::v-deep .vxe-table--fixed-left-wrapper {
  //   height: 207px !important;
  // }
}

.customer-search {
  ::v-deep .vxe-table--body-wrapper {
    height: revert !important;
  }
}
// .sirui-table .vxe-toolbar[data-v-3c6ed471]
// .SiruiModalHeight {
//   ::v-deep .sirui-table .vxe-toolbar {
//     display: none !important;
//   }
// }
</style>
